package XML与JSON.使用DOM4J;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class DOM4J修改xml {

   public static void main(String[] args) {
   
      try {
      	SAXReader reader = new SAXReader();
         //File inputFile = new File("input.txt");
         //Document document = reader.read( inputFile );
         
         File inputFile = new File("src\\main\\java\\XML与JSON\\使用DOM4J\\input.txt");
         OutputStream output=new FileOutputStream("src\\main\\java\\XML与JSON\\使用DOM4J\\output1.txt");
         Document document = reader.read( inputFile );

         Element classElement = document.getRootElement();

         List<Node> nodes = document.selectNodes("/class/student[@rollno = '493']" );//选择属性为rollno="493"的student
         
         for (Node node : nodes) {
            Element element = (Element)node;
            Iterator<Element> iterator = element.elementIterator("marks");

            System.out.println(element.getName());
            while(iterator.hasNext()) {
               Element marksElement = (Element)iterator.next();
               marksElement.setText("80");
            }
         }

         // Pretty print the document to System.out
         OutputFormat format = OutputFormat.createPrettyPrint();//完美型多行输出格式
         XMLWriter writer;
         writer = new XMLWriter( System.out, format );//控制台输出
         writer = new XMLWriter( output, format );//写入文件
         writer.write( document );
      } catch (DocumentException e) {
         e.printStackTrace();
      } catch (UnsupportedEncodingException e) {         
         e.printStackTrace();
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}